package com.akol.seret.webApiEntities.Requests;

import com.akol.seret.webApiEntities.Requests.BasicRequestMessage;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;

/**
 * Created by Gad on 18/02/2015.
 */
public class RequestClassAdapter implements
        JsonSerializer<BasicRequestMessage>,
        JsonDeserializer<BasicRequestMessage> {

    @Override
    public JsonElement serialize(BasicRequestMessage src, Type typeOfSrc,
                                 JsonSerializationContext context) {
        JsonObject result = new JsonObject();
        result.add("type", new JsonPrimitive(src.getClass().getSimpleName()));
        GsonBuilder builder = new GsonBuilder();
        result.add("properties", builder.create().toJsonTree(src, typeOfSrc));
        return result;
    }

    @Override
    public BasicRequestMessage deserialize(JsonElement json, Type typeOfT,
                                           JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();
        String type = jsonObject.get("type").getAsString();
        JsonElement element = jsonObject.get("properties");

        try {
            String thepackage = "webApiEntities.Requests.";
            GsonBuilder builder = new GsonBuilder();
            return (BasicRequestMessage) builder.create().fromJson(element,
                    Class.forName(thepackage + type));
        } catch (ClassNotFoundException cnfe) {
            throw new JsonParseException("Unknown element type: " + type, cnfe);
        }
    }
}